package com.lj.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.common.constant.BaseConstant;
import com.lj.common.core.redis.RedisCache;
import com.lj.system.mapper.SysConfigMapper;
import com.lj.system.model.SysConfig;
import com.lj.system.service.ISysConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 系统配置服务实现类
 *
 * @author 小李飞刀
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    @Resource
    private SysConfigMapper configMapper;

    @Resource
    private RedisCache<String, String> redisCache;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = this.list();
        for (SysConfig config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }


    /**
     * 查询是否开启验证码
     *
     * @return 是否
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        return Convert.toBool(captchaOnOff);
    }

    /**
     * 根据键值查询
     *
     * @param configKey 配置键值
     * @return 结果
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = redisCache.getCacheObject(getCacheKey(configKey));
        if (CharSequenceUtil.isNotEmpty(configValue)) {
            return configValue;
        }
        QueryWrapper<SysConfig> config = Wrappers.query();
        config.eq("config_key", configKey);
        SysConfig retConfig = configMapper.selectOne(config);
        if (ObjectUtil.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return CharSequenceUtil.EMPTY;
    }

    /**
     * 获取缓存键值
     *
     * @param configKey 键值名称
     * @return 结果
     */
    private String getCacheKey(String configKey) {
        return BaseConstant.SYS_CONFIG_KEY + configKey;
    }

}
